package com.chenailin.www.controller.auth;

import com.chenailin.www.exception.BusinessException;
import com.chenailin.www.model.vo.ResultVO;
import com.chenailin.www.service.EmailService;
import com.chenailin.www.service.VerificationCodeService;
import com.chenailin.www.serviceimpl.EmailServiceImpl;
import com.chenailin.www.serviceimpl.VerificationCodeServiceImpl;
import com.chenailin.www.util.JsonUtil;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author evi
 */
@WebServlet("/email-code")
public class EmailController extends HttpServlet {
    private static final Logger logger = LoggerFactory.getLogger(EmailController.class);
    private final EmailService emailService = new EmailServiceImpl();
    private final VerificationCodeService verificationCodeService = new VerificationCodeServiceImpl();

    @Override
    public void init() throws ServletException {
        System.out.println("EmailController 初始化完成");
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("收到请求，方法: " + req.getMethod());
        super.service(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=UTF-8");
        try {
            // 1. 读取并解析JSON请求体
            BufferedReader reader = req.getReader();
            Map<String, String> params = JsonUtil.fromJson(IOUtils.toString(reader), Map.class);
            String email = params.get("email");

            // 3. 发送验证码
            logger.info("准备发送验证码到邮箱: {}", email);
            verificationCodeService.sendVerificationCode(email);

            // 4. 返回成功响应 ???
            sendJsonResponse(resp, HttpServletResponse.SC_ACCEPTED,"验证码发送成功");
            logger.info("验证码发送成功: {}", email);

        } catch (BusinessException e) {
            logger.warn("业务异常: {}", e.getMessage());
            sendJsonResponse(resp, HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        } catch (Exception e) {
            logger.error("系统异常", e);
            sendJsonResponse(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "系统繁忙");
        }
    }

//    @Override
//    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        resp.setContentType("application/json;charset=UTF-8");
//
//        try {
//            // 1. 读取请求体
//            BufferedReader reader = req.getReader();
//            Map<String, String> requestData = JsonUtil.fromJson(IOUtils.toString(reader), Map.class);
//            String email = requestData.get("email");
//
//            // 2. 参数校验
//            if (email == null || email.trim().isEmpty()) {
//                logger.warn("邮箱参数为空");
//                resp.getWriter().write(JsonUtil.toJson(ResultVO.error(400, "邮箱不能为空")));
//                return;
//            }
//
//            // 3. 发送验证码
//            logger.info("准备发送验证码到邮箱: {}", email);
//            emailService.sendVerificationCode(email);
//
//            // 4. 返回成功响应
//            resp.getWriter().write(JsonUtil.toJson(ResultVO.success("验证码发送成功")));
//            logger.info("验证码发送成功: {}", email);
//
//        } catch (IllegalArgumentException e) {
//            logger.warn("参数验证失败: {}", e.getMessage());
//            resp.getWriter().write(JsonUtil.toJson(ResultVO.error(400, e.getMessage())));
//        } catch (Exception e) {
//            logger.error("发送验证码失败", e);
//            resp.getWriter().write(JsonUtil.toJson(ResultVO.error(500, "系统繁忙，请稍后重试")));
//        }
//    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=UTF-8");
        resp.setHeader("X-Content-Type-Options", "nosniff");

        resp.getWriter().write(JsonUtil.toJson(
                ResultVO.error(405, "请使用POST方法请求此接口")
        ));

    }

    private void handleSendRegisterCode(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 1. 从请求体解析 JSON
        try (BufferedReader reader = req.getReader()) {
            String requestBody = IOUtils.toString(reader);
            Map<String, String> params = JsonUtil.fromJson(requestBody, Map.class);
            String email = params.get("email");
//            try (BufferedWriter writer = new BufferedWriter(new FileWriter("/D:/code/cat/Cloud/email_log.txt", true))) {
//                writer.write("获取到的邮箱地址111: " + email + "\n");
//            } catch (IOException ex) {
//                ex.printStackTrace();
//            }
//            System.out.println("邮箱" + email);
            logger.info("获取到的邮箱地址: {}", email);
            if (email == null || email.isEmpty()) {
                sendJsonResponse(resp, HttpServletResponse.SC_BAD_REQUEST, "邮箱不能为空");
                return;
            }

            logger.info("开始发送验证码到邮箱: {}", email);
//            // 2. 发送验证码
//            try (BufferedWriter writer = new BufferedWriter(new FileWriter("/D:/code/cat/Cloud/email_log.txt", true))) {
//                writer.write("验证码已存储，邮箱authcontroller: " + email + ", 验证码: " + "\n");
//            } catch (IOException ex) {
//                ex.printStackTrace();
//            }
            verificationCodeService.sendVerificationCode(email);
//            sendJsonResponse(resp, ResultVO.success("验证码发送成功"));
            logger.info("成功发送验证码到邮箱: {}", email);
        } catch (BusinessException e) {
            System.out.println("发送验证码时业务异常: {}"+ e.getMessage()+ e);
//            sendJsonResponse(resp, ResultVO.error(e.getMessage()));
        } catch (IOException e) {
            System.out.println("读取请求体或发送响应时出现 I/O 异常: {}"+ e.getMessage()+ e);
            sendJsonResponse(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "读取或发送数据时出错");
        } catch (Exception e) {
            System.out.println("发送验证码时出现未知异常: {}"+ e.getMessage()+ e);
            sendJsonResponse(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "系统繁忙");
        }
    }

    /**
     * 发送JSON格式响应
     */
    private void sendJsonResponse(HttpServletResponse resp, int statusCode, String message) throws IOException {
        resp.setStatus(statusCode);
        Map<String, Object> responseMap = new HashMap<>();
        responseMap.put("code", statusCode);
        responseMap.put("message", message);
        resp.getWriter().write(JsonUtil.toJson(responseMap));
    }
}